//
//  CCWindow.m
//  SDKUI
//
//  Created by aiquantong on 22/08/2017.
//  Copyright © 2017 aiquantong. All rights reserved.
//


#import "CCCallWindow.h"
#import "CallManager.h"

#import "CCCallViewController.h"
#import "CCMPVCallViewController.h"

@interface CCCallWindow ()
{
    UIButton *bt;
}

@end

@implementation CCCallWindow

static CCCallWindow *shareInstance = nil;

+(CCCallWindow *)shareInstance
{
    static dispatch_once_t one;
    dispatch_once(&one, ^{
        if (shareInstance == nil) {
            shareInstance = [[CCCallWindow alloc] init];
        }
    });
    return shareInstance;
}


//radio width/height
+(CGSize)adjustSizeToRadio:(float)radio persentSize:(CGSize)pSize;
{
    if (radio < 0.01) {
        return pSize;
    }
    
    //防止出现数字不准
    if (radio < 0.5f) {
        radio = 1.0f;
    }else if(radio > 2.0f){
        radio = 1.0f;
    }
    
    CGRect rect = CGRectMake(0, 0, pSize.width, pSize.height);
    CGRect withRect  = CGRectMake(0, 0, pSize.width, pSize.width/radio);
    CGRect heightRect = CGRectMake(0, 0, pSize.height*radio, pSize.height);
    
    if (CGRectContainsRect(rect, withRect)) {
        return withRect.size;
    }else if(CGRectContainsRect(rect, heightRect)){
        return heightRect.size;
    }else{
        return pSize;
    }
}


static BOOL isHiddenInWindow = YES;
/**
 显示call view 在window中
 */
-(void)showInWindowWtihViewController:(UIViewController *)callViewController;
{
    dispatch_after(
                   dispatch_time(DISPATCH_TIME_NOW,(int64_t)(0.05 * NSEC_PER_SEC)),
                   dispatch_get_main_queue(),
                   ^{
                       
                       UIWindow *currentKeyWindow = [UIApplication sharedApplication].keyWindow;
                       
                       CGRect screenRect = [UIScreen mainScreen].bounds;
                       CGRect startFrame = CGRectMake(0,
                                                      -screenRect.size.height,
                                                      screenRect.size.width,
                                                      screenRect.size.height);
                       
                       CGRect endFrame = CGRectMake(0,
                                                    0,
                                                    screenRect.size.width,
                                                    screenRect.size.height);
                       
                       self.backgroundColor = [[UIColor yellowColor] colorWithAlphaComponent:0.0];
                       self.frame = startFrame;
                       self.userInteractionEnabled = YES;
                       self.exclusiveTouch = YES;
                       
                       self.windowLevel = UIWindowLevelAlert;
                       self.rootViewController = callViewController;
                       [self makeKeyAndVisible];
                       
                       [currentKeyWindow makeKeyWindow];
                       
                       [UIView
                        animateWithDuration:0.35
                        animations:^{
                            self.frame = endFrame;
                        }
                        completion:^(BOOL finished) {
                            isHiddenInWindow = NO;
                            
                        }];
                   });
}


/**
 隐藏call view 在window中
 */
-(void)hiddenInWindow;
{
    if (isHiddenInWindow == NO) {
        isHiddenInWindow = YES;
    }else{
        return;
    }
    
    [[UIDevice currentDevice] setValue:@(UIDeviceOrientationPortrait) forKey:@"orientation"];
    [UIViewController attemptRotationToDeviceOrientation];
    
    //CGRect startFrame = showWindow.frame;
    CGRect screenRect = self.frame;
    
    CGRect endFrame = CGRectMake(screenRect.origin.x,
                                 -screenRect.size.height,
                                 screenRect.size.width,
                                 screenRect.size.height);
    
    [UIView animateWithDuration:0.35
                     animations:^{
                         self.frame = endFrame;
                     }
                     completion:^(BOOL finished) {
                         [self setHidden:YES];
                         [self removeFromSuperview];
                         [[CallManager shareInstance] showLastTerminateReason];
                     }];
}


-(void)minWindowWithAnimation:(void(^)(void))anmination completion:(void(^)(BOOL finished))callback;
{
    
    [UIView animateWithDuration:0.35 animations:^{
        [[UIDevice currentDevice] setValue:@(UIDeviceOrientationPortrait) forKey:@"orientation"];
        [UIViewController attemptRotationToDeviceOrientation];
    } completion:^(BOOL finished) {
        
        CGRect screenRect = [UIScreen mainScreen].bounds;
        CGRect endFrame = CGRectMake(screenRect.size.width - minScreen_Width - 20,
                                     20,
                                     minScreen_Width,
                                     minScreen_Height);
        
        [UIView animateWithDuration:0.35
                         animations:^{
                             self.frame = endFrame;
                             if (anmination) {
                                 anmination();
                             }
                             [self setNeedsDisplay];
                         }
                         completion:^(BOOL finished) {
                             bt = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, minScreen_Width, minScreen_Height)];
                             bt.backgroundColor = [UIColor clearColor];
                             bt.userInteractionEnabled = YES;
                             
                             UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(handlePanGesture:)];
                             pan.delaysTouchesBegan = YES;
                             [bt addGestureRecognizer:pan];
                             [bt addTarget:self action:@selector(onclickMax:) forControlEvents:UIControlEventTouchUpInside];
                             [self addSubview:bt];
                             if (callback) {
                                 callback(finished);
                             }
                             [self setNeedsDisplay];
                         }];
    }];
}


-(IBAction)onclickMax:(id)sender
{
    if(bt){
        [bt removeFromSuperview];
    }
    [self maxWindow];
}


-(void)maxWindow;
{
    
    if ([self.rootViewController isKindOfClass:[CCCallViewController class]]) {
        [((CCCallViewController *)self.rootViewController) maxInWindow:0];
    }else if ([self.rootViewController isKindOfClass:[CCMPVCallViewController class]]) {
        [((CCMPVCallViewController *)self.rootViewController) maxInWindow:0];
    }else{
        
    }
    
    CGRect screenRect = [UIScreen mainScreen].bounds;
    [UIView animateWithDuration:0.35
                     animations:^{
                         self.frame = screenRect;
                         if ([self.rootViewController isKindOfClass:[CCCallViewController class]]) {
                             [((CCCallViewController *)self.rootViewController) maxInWindow:1];
                         }else if ([self.rootViewController isKindOfClass:[CCMPVCallViewController class]]) {
                             [((CCMPVCallViewController *)self.rootViewController) maxInWindow:1];
                         }else{
                             
                         }
                     }
                     completion:^(BOOL finished) {
                         if ([self.rootViewController isKindOfClass:[CCCallViewController class]]) {
                             [((CCCallViewController *)self.rootViewController) maxInWindow:2];
                         }else if ([self.rootViewController isKindOfClass:[CCMPVCallViewController class]]) {
                             [((CCMPVCallViewController *)self.rootViewController) maxInWindow:2];
                         }else{
                             
                         }
                     }];
    
}


#pragma mark - event response
- (void)handlePanGesture:(UIPanGestureRecognizer*)p
{
    UIWindow *appWindow = [UIApplication sharedApplication].delegate.window;
    CGPoint panPoint = [p locationInView:appWindow];
    
    if(p.state == UIGestureRecognizerStateBegan) {
        
    }else if(p.state == UIGestureRecognizerStateChanged) {
        NSLog(@"appWindow Rect == %@  windowCenter == %@",
              NSStringFromCGRect(appWindow.frame), NSStringFromCGPoint(panPoint));
        self.center = panPoint;
        
    }else if(p.state == UIGestureRecognizerStateEnded
             || p.state == UIGestureRecognizerStateCancelled) {
        
        CGFloat ballWidth = self.frame.size.width;
        CGFloat ballHeight = self.frame.size.height;
        CGFloat screenWidth = appWindow.bounds.size.width;
        CGFloat screenHeight = appWindow.bounds.size.height;
        
        float x = self.center.x;
        float y = self.center.y;
        
        if (x < ballWidth / 2) {
            x = ballWidth / 2;
        }else if(x > screenWidth - ballWidth / 2){
            x = screenWidth - ballWidth / 2;
        }
        
        if (y < ballHeight / 2) {
            y = ballHeight / 2;
        }else if(y > screenHeight - ballHeight / 2){
            y = screenHeight - ballHeight / 2;
        }
        
        NSLog(@"appWindow Rect == %@  windowCenter == %@",
              NSStringFromCGRect(appWindow.frame),
              NSStringFromCGPoint(CGPointMake(x, y)));
        
        [UIView animateWithDuration:.25 animations:^{
            self.center = CGPointMake(x, y);
        }];
    }else{
        NSLog(@"pan state : %zd", p.state);
    }
}




//- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
//{
//    UIView *retView = nil;
//    NSLog(@"hitTest %@ Entry! event=%@", @"", event);
//    
//    retView = [super hitTest:point withEvent:event];
//    NSLog(@"hitTest %@ Exit! view = %@", @"", retView);
//    
//    return retView;
//}
//
//
//- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
//{
//    BOOL ret = [super pointInside:point withEvent:event];
//    if (ret) {
//        NSLog(@"pointInside = YES");
//    } else {
//        NSLog(@"pointInside = NO");
//    }
//    return ret;
//}


@end
